#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#include "../include/meta.h"
#include "../include/vfs_errorcodes.h"

struct list* substring_search(char*);

char* search_file(char* prefix_files_name,char* output_file)
	{
	char result[100];
	char opfile[100];
	strcpy(opfile,output_file);
	if((strcmp(prefix_files_name,"")==0)||(strcmp(output_file,"")==0))
		{
		strcpy(result,"searchfile_FAILURE ");
		strcat(result,ERR_VFS_SEARCHFILE_00);
		sprintf(str,"%s",result);
		return str;
		}
	//char filepath[30]="kjbk";
	char *ext= strrchr(opfile,'.');
	if(ext==NULL)
	{
		strcat(opfile,".txt");
	}
	//printf("%s",opfile);

	if(root==NULL)
		{
		strcpy(result,"searchfile_FAILURE ");
		strcat(result,ERR_VFS_SEARCHFILE_02);
		sprintf(str, "%s",result);
		return str;
		}	

	FILE *fp_search;
	int count=0;
	char test[10];
	fp_search=fopen(opfile,"w");
	if(fp_search == NULL)
		{
		strcpy(result,"searchfile_FAILURE ");
		strcat(result,"CANNOT_CREATE_FILE");
		sprintf(str, "%s",result);
		return str;
		}
	struct list* result_set=(struct list *)malloc(sizeof(struct list));
	result_set=substring_search(prefix_files_name);

	if (result_set==NULL)
		{	
			fprintf(fp_search,"%s ","");
		}
	else
		{
			while (result_set!=NULL)
				{
					
					fprintf(fp_search,"%s ",result_set->filename);
					fprintf(fp_search,"%s \n",result_set->pathname);
					count=count+1;
					result_set=result_set->next;
				}
		}
		fclose(fp_search);
		//itoa(count,test,10);
		sprintf(test,"%d",count);
		//printf("count: %s \n ",test);
		//strcpy(test,count);
		strcpy(result,"searchfile_SUCCESS ");
		strcat(result,test);
		sprintf(str, "%s",result);
		return str;
	}
struct list* substring_search(char *start_filesname)
{       int index,length;
        struct list *start,*fresh,*temp,*head;
        head=(struct list *)malloc(sizeof(struct list));
        temp=head;
        index = hash(start_filesname);
        start=hash_table[index];
        length=strlen(start_filesname);
        if(hash_table[index] == NULL)
        {
                return NULL;
        }
        else if(index == -1)
        {
                return NULL;
        }
        else{
                        while(start!=NULL)
                {      
                        if (strncmp(start->filename,start_filesname,length)==0)
                           {    
                                fresh= (struct list *)malloc(sizeof(struct list));
                                strcpy(fresh->pathname,start->pathname);  
                                strcpy(fresh->filename,start->filename);                
                                fresh->next=NULL;
                                temp->next=fresh;
                                temp=fresh;              
                           }
                        start = start->next;
                }
               
        }
          return head->next;
}
